package com.jjkj.controller;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Page;
import com.jjkj.base.common.R;
import com.jjkj.base.interceptor.JwtInterceptor;
import com.jjkj.domain.dto.UpdateUserDto;
import com.jjkj.domain.dto.UserDto;
import com.jjkj.domain.vo.UserVo;
import com.jjkj.model.User;
import com.jjkj.service.UserService;
import io.jboot.db.model.Columns;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import net.sf.cglib.beans.BeanCopier;

@RequestMapping("/user")
public class UserController extends JbootController {
    @Inject
    private UserService userService;

    /**
     * 获取用户信息
     */
    public void info(){
        String userId = getJwtPara("userId");
        User user = userService.findById(userId);
        UserVo userVo = new UserVo();
        userVo.setUsername(user.getUsername());
        renderJson(R.success(userVo));
    }

    @Clear(JwtInterceptor.class)
    public void logout(){
        renderJson(R.success());
    }

    public void user(int id) {
        renderJson(userService.findById(id));
    }

    public void userList() {
        int page = getParaToInt("page", 1);
        int limit = getParaToInt("limit", 20);
        Page<User> userPage = userService.paginate(page, limit);
        renderJson(R.success(userPage));
    }

    public void createUser(){
        UserDto user = getRawObject(UserDto.class);

        if(user == null){
            renderJson(R.error("发生错误"));
            return;
        }

        if(StrUtil.isBlank(user.getUsername())) {
            renderJson(R.error("请输入用户名"));
            return;
        }

        if(StrUtil.isBlank(user.getPassword())) {
            renderJson(R.error("请输入密码"));
            return;
        }

        Object u = userService.save(new User() {{
            setUsername(user.getUsername());
            setPassword(HashKit.md5(user.getPassword()));
        }});
        renderJson(R.success(u));
    }

    public void deleteUser(int id) {
        renderJson(R.success(userService.deleteById(id)));
    }

    public void updateUser() {
        UpdateUserDto user = getRawObject(UpdateUserDto.class);

        if(user == null){
            renderJson(R.error("发生错误"));
            return;
        }

        User userModel = userService.findFirstByColumns(Columns.create("username", user.getUsername()));

        if(userModel == null){
            renderJson(R.error("未找到对应的用户"));
            return;
        }

        if(StrUtil.isBlank(user.getPassword())) {
            renderJson(R.error("请输入密码"));
            return;
        }

        userModel.setPassword(HashKit.md5(user.getPassword()));

        Object u = userService.update(userModel);
        renderJson(R.success(u));
    }
}
